<script>
import {getUserId} from "@/utils/auth";
import {getUnreadNum} from "@/api/chat";
import useUserStore from '@/store/user.js'
import {getUnreadNotificationNum} from "@/api/notification";
import WebsocketHeartbeat from 'websocket-heartbeat-miniprogram';

export default {
  data() {
    return {
      socketTask: null,
      heartBeatInterval: null,
    }
  },
  onLaunch(options) {
    // 在应用初始化时连接 WebSocket


  },
  onUnload() {
    // 当页面卸载或应用退出时清除心跳定时器和关闭WebSocket连接
    // clearInterval(this.heartBeatInterval);
    // if (this.socketTask) {
    //   this.socketTask.close();
    // }
  },
  onShow() {
    let userId = getUserId();
    if (userId !== null && userId !== '' && userId !== undefined) {
      this.initWebSocket(this.$CHAT_URL.replace("https://", "wss://").replace("http://", "ws://") + "/websocket/" + getUserId());
    }
    console.log('App Show')
    //⭐隐藏pages.json里配置的导航栏，使用封装的tabbar组件
    uni.hideTabBar({
      animation: false
    })
  },
  onHide: function () {
  },
  methods: {
    async initWebSocket(url) {
      var that = this
      let task = await WebsocketHeartbeat({
        miniprogram: wx,
        pingTimeout: 2000,
        connectSocketParams: {
          url: url,
        },
      });
      useUserStore().setSocketTask(task)
      task.onOpen = () => { //钩子函数
      };
      task.onClose = () => { //钩子函数
      };
      task.onError = e => { //钩子函数
      };
      task.onMessage = msg => { //钩子函数
        console.log('onMessage', msg);
        let parse = msg.data;
        uni.$emit('websocketMessage', parse);

        if (JSON.parse(parse)?.id !== undefined) {
          let unreadMessageNumber = useUserStore().unreadMessageNumber;
          unreadMessageNumber++
          useUserStore().setUnreadMessageNumber(Number(unreadMessageNumber));
        }

        // 处理收到的消息

      };
      task.onReconnect = () => { //钩子函数
        console.log('reconnect...');
      };
      task.socketTask.onOpen(data => { //原生实例注册函数，重连后丢失
        console.log('socketTask open');
      });
      task.socketTask.onMessage(data => { //原生实例注册函数，重连后丢失
        console.log('socketTask data');
      });
      // })
    },
    // initWebSocket(userId) {
    //   this.socketTask = uni.connectSocket({
    //     url: this.$CHAT_URL.replace("https://", "wss://")
    //         .replace("http://", "ws://") + "/websocket/" + getUserId(),
    //     success: () => {
    //       this.getMessageNum()
    //       console.log('WebSocket连接成功');
    //       // 成功连接后启动心跳机制
    //       this.startHeartbeat();
    //     },
    //     fail: (err) => {
    //       console.error('WebSocket连接失败', err);
    //     },
    //   });
    //
    //   uni.onSocketMessage((res) => {
    //     console.log('Received WebSocket message:', res);
    //     let unreadMessageNumber = useUserStore().unreadMessageNumber;
    //     unreadMessageNumber++
    //     useUserStore().setUnreadMessageNumber(Number(unreadMessageNumber));
    //     // 处理收到的消息
    //     uni.$emit('websocketMessage', JSON.parse(res.data));
    //   });
    //   uni.onSocketError((err) => {
    //     console.log('WebSocket连接发生错误', err);
    //   });
    //   // 监听关闭事件并实现重连
    //   uni.onSocketClose((res) => {
    //     console.log('WebSocket连接已关闭，原因：', res);
    //     this.reconnectWebSocket();
    //   });
    // },
    // reconnectWebSocket() {
    //   if (this.socketTask) {
    //     this.socketTask.close();
    //   }
    //   setTimeout(() => {
    //     this.initWebSocket();
    //   }, 3000); // 根据实际情况调整重连间隔时间
    // },
    // startHeartbeat() {
    //   this.heartBeatInterval = setInterval(() => {
    //     if (this.socketTask && this.socketTask.readyState === this.socketTask.OPEN) {
    //       this.socketTask.send({data: 'HeartBeat'});
    //     }
    //   }, 30000); // 每30秒发送一次心跳，可自定义间隔
    // },
    // async getMessageNum() {
    //   const res1 = await getUnreadNum()
    //   const res2 = await getUnreadNotificationNum()
    //   useUserStore().setUnreadMessageNumber(res1.data + res2.data)
    //
    // },
    // async getNotificationNum() {
    //
    //   let unreadMessageNumber = useUserStore().unreadMessageNumber;
    //   if (res.data !== null && res.data !== undefined) {
    //     if (typeof res.data === 'number' && !isNaN(res.data) && isFinite(res.data)) {
    //       useUserStore().setUnreadMessageNumber(Number(unreadMessageNumber) + Number(res.data));
    //
    //     }
    //   }
    //
    //
    // }
  },

}
</script>

<style lang="scss">
@import "@/uni_modules/uview-plus/index.scss";
@import "@/static/iconfont/iconfont.css";
</style>
